package com.diorsunion.hedge.bo.sms;

import com.alibaba.fastjson.JSON;
import com.diorsunion.hedge.common.ServiceResult;
import com.diorsunion.hedge.domain.SMS;
import com.diorsunion.hedge.util.LogUtil;
import com.google.common.base.Joiner;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaAliqinFcSmsNumSendRequest;
import com.taobao.api.response.AlibabaAliqinFcSmsNumSendResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;

/**
 * 阿里大鱼短信接口
 * Created by wanglaoshi on 2016/4/23.
 */
@Service("AliDaYuSMSBO")

public class AliDaYuSMSBO implements SMSBO {
    @Value("${taobaoapi.serverUrl}")
    String serverUrl;
    @Value("${taobaoapi.appKey}")
    String appKey;
    @Value("${taobaoapi.appSecret}")
    String appSecret;

    Joiner joiner = Joiner.on(',');
    @Override
    public ServiceResult sendMessage(SMS sms) {
        TaobaoClient client = new DefaultTaobaoClient(serverUrl, appKey, appSecret);
        AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
        req.setSmsType("normal");
        req.setSmsFreeSignName(sms.signName);
        req.setSmsParam( JSON.toJSONString(sms.params));
        req.setRecNum(joiner.join(sms.recTelSet));
        req.setSmsTemplateCode(sms.templateCode);
        try {
            AlibabaAliqinFcSmsNumSendResponse response = client.execute(req);
            if(response!=null && response.isSuccess() && response.getResult()!=null){
                return ServiceResult.successResult(response.getResult().getModel());
            }
            return ServiceResult.returnResult(response.getSubCode(), response.isSuccess(), response.getSubMsg());
        } catch (ApiException e) {
            LogUtil.error(LogUtil.net,req.toString()+" error",e);
            return ServiceResult.returnResult(false,e.toString());
        }
    }
}
